<?php
declare(strict_types=1);

namespace app\model;

use think\facade\Config;

class FileManager extends \think\Model
{
    protected $pk = "fileid";

    protected $schema = [
        'fileid'        => "int",      // '文件id'
        'filename'      => "varchar",  // '文件名称'
        'filesize'      => "int",      // '文件大小字节'
        'filetime'      => "int",      // '文件上传时间'
        'filepath'      => "varchar",  // '文件路径'
        'fileextension' => "varchar",  // '文件扩展名'
        'title'         => "varchar",  // '文件title'
        'type'          => "int",      // '0为附件,1为图片,2为Flash文件,3为多媒体文件'
        'onclick'       => "int",      // '下载量'
        'username'      => "varchar",  // '上传者'
        'cid'           => "int",      // '栏目ID'
        'infoid'        => "int",      // '信息ID', 
        'cjid'          => "int",       // '信息临时ID'
        'hash_md5'       => "varcahr"       // hash值(MD5)
    ];

    protected $autoWriteTimestamp = false;

    public static function queryPage(array $param = [])
    {
        $limit = (int)$param['limit'];

        $where = [];

        return self::where($where)->field('fileid,filename,filesize,filetime,filepath,fileextension,title,username')->paginate(['list_rows'=>$limit, 'query' => $param]);
    }

    public static function saveFileInfo(\think\File $file)
    {
        $fileinfo = self::where('hash_md5', $file->md5())->find();

        $publicRootPath = str_replace('\\', '/', Config::get('filesystem.disks.public.root'));

        $publicUrlPath =  Config::get('filesystem.disks.public.url');

        if ($fileinfo == null) {
            $fileinfo = new static();
        } elseif ($publicRootPath . $fileinfo->filepath == $file->getPathname())  { // 路径不同的文件
            $fileinfo = new static();
        }

        $fileinfo->filename       = $file->getFilename();
        $fileinfo->filesize       = $file->getSize();
        $fileinfo->filetime       = $file->getCTime();
        $fileinfo->filepath       = $publicUrlPath . str_replace($publicRootPath, '', $file->getPathname());
        $fileinfo->fileextension  = $file->getExtension();
        $fileinfo->username       = 'system';
        $fileinfo->hash_md5       = $file->md5();

        $fileinfo->save();
    }
}
